/* * * * * * * * * * * * * * * * * * * *
 * Karlan Mitchell (C) 2004-2006       *
 * karlanmitchell@gmail.com            *
 * This source is LGPL                 *
 * * * * * * * * * * * * * * * * * * * */
 
/* * * * * * * * * * * * * * * * * * * *
 * env.h:  Functions which modify      *
 * the program's environment, such as  *
 * changing the current working        *
 * directory.                          *
 * This is where most of the           *
 * cross-platform base is found        * 
 * * * * * * * * * * * * * * * * * * * */

#include "env.h"

#ifndef WIN32
int simple_mkdir(char * dirname){
	return mkdir(dirname, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
	}
#endif

#ifndef WIN32
int GetTempPath(size_t nBufferLength, char *lpBuffer){
    strncpy(lpBuffer, "/tmp/", nBufferLength);
    return 1;
    }
#endif

int setcwd(char * Dir){
		#ifdef WIN32
                   return SetCurrentDirectory(Dir);
		#else
           	   if(chdir(Dir) == 0)
	   	        return 1;
               else
	   	       return 0;
		#endif
        }

int create_tmp_file(char * seed, char * filename, size_t filename_len){
    char tmp_path[PATH_MAX];
    GetTempPath(PATH_MAX, tmp_path);

    char test_buf[PATH_MAX];

    int unsigned counter = 0; 

    srand(time(NULL));

    int random = 0;

    /*First just try the file name, plain*/
    snprintf(test_buf, PATH_MAX, "%s%s", tmp_path, seed);
    if(is_file(test_buf))
	random = 1;

    while(random){
	if(strchr(seed, '/') == NULL && strchr(seed, '\\') == NULL)
		snprintf(test_buf, PATH_MAX, "%s%d_%c%c%c%c_%s", tmp_path, counter, rand() % 26 + 'A',  rand() % 26 + 'A',  rand() % 26 + 'A',  rand() % 26 + 'A', seed);
	else
		snprintf(test_buf, PATH_MAX, "%stmpfile_%d_%c%c%c%c", tmp_path, counter, rand() % 26 + 'A',  rand() % 26 + 'A',  rand() % 26 + 'A',  rand() % 26 + 'A');
	if(counter >= 0xFFFFFF)
		return -1;
	if(!is_file(test_buf))
		break;
	counter++;
	}


    strlcpy(filename, test_buf, filename_len);

     FILE * quick_open = fopen(filename, "wb");
      fwrite(".", 1, 1, quick_open);
     fclose(quick_open);
    return 0;
    }

#ifdef WIN32_OLD_NOUSE
int getcwd(char * buffer, size_t buflen){
		#ifdef WIN32
                   return GetCurrentDirectory(buflen, buffer);
		#else
           	   char * cwd = getenv("CWD");
           	   if(cwd == NULL)
           	          strlcpy(buffer, "", buflen);
               else
           	      strlcpy(buffer, cwd, buflen);
           	      return 0;
		#endif
        }
#endif
